package com.sgb.member;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.member.databinding.ActivityMainMemberLoginBinding;
import com.sgb.member.entity.MemberCompanyBean;
import com.sgb.member.ui.fragment.HomeMemberFragment;
import com.swgk.core.base.AppActivity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

@Route(path = MemberConfig.ROUTE_MAIN)
public class MemberMainActivity extends AppActivity {

    private static final int PERMISSION_REQUEST_CODE = 10201;

    private ActivityMainMemberLoginBinding mBinding;
    private MainModel sModel;

    private AppCompatSpinner spinner;

    private boolean isDebug;

    public static void start(Context context) {
        Intent intent = new Intent(context, MemberMainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        super.initView();
        isDebug = BuildConfig.IS_MODULE_DEBUG;
        sModel = new ViewModelProvider(this).get(MainModel.class);
        if (isDebug) {
            mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main_member_login);
            TextView textView = findViewById(R.id.title_view);
            ImageView imageView = findViewById(R.id.iv_back);
            spinner = findViewById(R.id.spinner);
            textView.setText("会员");
            imageView.setOnClickListener(v -> onBackPressed());
            if (!isPermissionGrated()) {
                requestPermission();
            }
            initUserInfos();
            initLogin();
        } else {
            setContentView(R.layout.activity_main_member);
            TextView tvTitle = findViewById(R.id.title_view);
            findViewById(R.id.iv_back).setOnClickListener(v -> onBackPressed());
            tvTitle.setText("会员");
            if (isPermissionGrated()) {
                loadFragment();
            } else {
                requestPermission();
            }
        }
    }

    private boolean isPermissionGrated() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 申请权限
     */
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if ((grantResults != null && grantResults.length > 0)) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    MToast.showToast(MemberMainActivity.this, "Storage or location permission is not granted");
                } else {
                    if (isDebug) {
                        return;
                    }
                    loadFragment();
                }
            }
        }
    }

    private void loadFragment() {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        HomeMemberFragment mHomeFragment = new HomeMemberFragment();
        fragmentTransaction.add(R.id.container, mHomeFragment);
        fragmentTransaction.setMaxLifecycle(mHomeFragment, Lifecycle.State.RESUMED);
        fragmentTransaction.commit();
    }

    private void initUserInfos() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LONGITUDE_ID, "108.95");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LATITUDE_ID, "34.27");
        sModel.companyList.observe(this, new Observer<List<MemberCompanyBean>>() {
            @Override
            public void onChanged(List<MemberCompanyBean> companyInfoEntities) {
                List<String> mData = new ArrayList<>();
                String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                for (int i = 0; i < companyInfoEntities.size(); i++) {
                    MemberCompanyBean companyInfoEntity = companyInfoEntities.get(i);
                    mData.add(companyInfoEntity.getName());
                    if (companyInfoEntity.getNo().equals(no)) {
                        spinner.setSelection(i, true);
                    }
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<>(MemberMainActivity.this, android.R.layout.simple_spinner_item, mData);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        MemberCompanyBean deptBean = companyInfoEntities.get(position);
                        sModel.settingMainCompany(deptBean);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }
        });
        sModel.mainCompany.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    MToast.showToast(MemberMainActivity.this, "设置成功");
                } else {
                    MToast.showToast(MemberMainActivity.this, "设置失败");
                }
            }
        });
    }

    private void initLogin() {
        mBinding.container.setVisibility(View.GONE);
        mBinding.loginLayout.setVisibility(View.VISIBLE);
        mBinding.editPhone.setText("17691090408");
        mBinding.editPws.setText("wz123456");
        mBinding.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = mBinding.editPhone.getText().toString();
                String pws = mBinding.editPws.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    MToast.showToast(MemberMainActivity.this, "请输入账号");
                    return;
                }
                if (TextUtils.isEmpty(pws)) {
                    MToast.showToast(MemberMainActivity.this, "请输入密码");
                    return;
                }
                sModel.pwdLoginModel(phone, pws);
            }
        });
        mBinding.jump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "");
                if (TextUtils.isEmpty(token)) {
                    return;
                }
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.IS_DATA, "会员成员");
                mBinding.container.setVisibility(View.VISIBLE);
                mBinding.loginLayout.setVisibility(View.GONE);
                loadFragment();
            }
        });
        mBinding.company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sModel.getCompanyList();
            }
        });

        String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            if (sModel.companyList == null || sModel.companyList.getValue() == null) {
                sModel.getCompanyList();
            }
        }
    }
}
